package com.ruoyi.cgq.esp32.controller;

import cn.hutool.json.JSONUtil;
import com.ruoyi.mqtt.config.MQTTClientUtils;
import com.ruoyi.mqtt.config.MqttResponseHolder;
import com.ruoyi.mqtt.consts.MqSensorsEnums;
import com.ruoyi.mqtt.dto.MqMessage;
import com.ruoyi.mytool.domain.WaterTempData;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.concurrent.TimeoutException;

import static com.ruoyi.mqtt.consts.MqSensorsEnums.SENSOR_REQUEST_TYPE_SEND;

/**
 * 获取传感器数据:主要用于获取温度，湿度，大气压数据
 */
@RequestMapping("/cgq/sensor")
@Controller
public class Sensor_AHT10_BMP20Controller {
    @Resource
    MqttResponseHolder responseHolder;
    @Resource
    MQTTClientUtils mqttService;
    @GetMapping("/readData")
    public ResponseEntity<WaterTempData> getRealtimeTemperature() {
        String requestId = responseHolder.createRequest();
        MqMessage mqMessage = new MqMessage();
        mqMessage.setRequestId(requestId);
        mqMessage.setRequestType(SENSOR_REQUEST_TYPE_SEND.getCode());
        mqMessage.setType(SENSOR_REQUEST_TYPE_SEND.getCode());
        // 发送带requestId的MQTT请求到设备
        mqttService.publish(MqSensorsEnums.TOPIC_ORANGEPI_RECEIVE_TEMP.getCode(), mqMessage);
        try {
            String cgaData = responseHolder.waitForResponse(requestId, 20);
            WaterTempData data  = JSONUtil.toBean(cgaData,WaterTempData.class);
            return ResponseEntity.ok(data);
        } catch (TimeoutException e) {
            return ResponseEntity.status(504).build();
        }
    }
}
